# 导入tkinter模块
import tkinter as tk
# 导入datetime模块，用于处理日期和时间，计算剩余时间
from datetime import datetime, timedelta


# 获取当前日期，current_date值类似：datetime.date(2024, 10, 11)
current_date = datetime.now().date()

# 定义初始化时间函数，初始化各个时间段
def initialize_times():
    # 定义全局变量，方便其他函数使用
    global start_time, lunch_break_start, lunch_break_end, end_time
    # 初始化时间变量，利用combine方法将日期和时间合并成一个datetime对象
    start_time = datetime.combine(current_date, datetime.strptime("09:00:00", "%H:%M:%S").time())
    lunch_break_start = datetime.combine(current_date, datetime.strptime("12:00:00", "%H:%M:%S").time())
    lunch_break_end = datetime.combine(current_date, datetime.strptime("13:30:00", "%H:%M:%S").time())
    end_time = datetime.combine(current_date, datetime.strptime("18:00:00", "%H:%M:%S").time())

# 调用初始化时间函数
initialize_times()

# 设置当前时间为上次更新时间
global last_update_time
last_update_time = datetime.now()

# 定义函数计算剩余时间
def calculate_remaining_time(current_time):
    if current_time < start_time:
        # 返回一个元组，包含剩余时间和提示信息
        return start_time - current_time, "上班剩余时间"
    elif current_time < lunch_break_start:
        return lunch_break_start - current_time, "上午上班剩余"
    elif current_time < lunch_break_end:
        return lunch_break_end - current_time, "午休结束剩余"
    elif current_time < end_time:
        return end_time - current_time, "下午下班剩余"
    else:
        # return timedelta(seconds=0), "已经下班"
        return current_time - end_time, "已经下班了"


# 更新倒计时
def update_countdown():
    current_time = datetime.now().replace(microsecond=0)# 舍弃微秒部分，以获取当前时间（以秒为单位）
    remaining_time, message = calculate_remaining_time(current_time)
    formatted_time = str(remaining_time).split(".")[0]# 按照小数点进行分割，只取整数部分
    hours, minutes, seconds = formatted_time.split(":")# 获取小时、分钟和秒
    label.config(
        text=f"【{message}】: {hours.zfill(2)}小时{minutes.zfill(2)}分钟{seconds.zfill(2)}秒"
    )
    root.after(1000, update_countdown)  # 每秒更新一次


# 开始移动窗口
def start_move(event):
    global x_start, y_start
    x_start = event.x
    y_start = event.y


# 停止移动窗口
def stop_move(event):
    pass  # 结束移动时可以不执行任何操作


# 在拖动过程中移动窗口
def do_move(event):
    delta_x = event.x - x_start
    delta_y = event.y - y_start
    geom = f"+{root.winfo_x() + delta_x}+{root.winfo_y() + delta_y}"
    root.geometry(geom)


# 关闭窗口
def close_window():
    root.destroy()


# 打开设置窗口
def open_settings():
    settings_window = tk.Toplevel(root)
    settings_window.title("设置")
    settings_window.geometry("300x300")
    # 计算设置窗口的位置
    root_x = root.winfo_x()
    root_y = root.winfo_y()
    # 将设置窗口放在主窗口下方
    settings_window.geometry(f"+{root_x}+{root_y + root.winfo_height()}")
    # 输入框和标签
    tk.Label(settings_window, text="上班时间:", font=("Arial", 12)).pack(pady=5)
    start_time_entry = tk.Entry(settings_window, font=("Arial", 12))
    start_time_entry.insert(0, start_time.strftime("%H:%M:%S"))  # 默认值
    start_time_entry.pack(pady=5)

    tk.Label(settings_window, text="午休开始时间:", font=("Arial", 12)).pack(pady=5)
    lunch_break_start_entry = tk.Entry(settings_window, font=("Arial", 12))
    lunch_break_start_entry.insert(0, lunch_break_start.strftime("%H:%M:%S"))  # 默认值
    lunch_break_start_entry.pack(pady=5)

    tk.Label(settings_window, text="午休结束时间:", font=("Arial", 12)).pack(pady=5)
    lunch_break_end_entry = tk.Entry(settings_window, font=("Arial", 12))
    lunch_break_end_entry.insert(0, lunch_break_end.strftime("%H:%M:%S"))  # 默认值
    lunch_break_end_entry.pack(pady=5)

    tk.Label(settings_window, text="下班时间:", font=("Arial", 12)).pack(pady=5)
    end_time_entry = tk.Entry(settings_window, font=("Arial", 12))
    end_time_entry.insert(0, end_time.strftime("%H:%M:%S"))  # 默认值
    end_time_entry.pack(pady=5)

    # 更新时间设置
    def update_times():
        try:
            global start_time, lunch_break_start, lunch_break_end, end_time, current_date
            new_start_time = datetime.strptime(
                start_time_entry.get(), "%H:%M:%S"
            ).time()
            new_lunch_break_start = datetime.strptime(
                lunch_break_start_entry.get(), "%H:%M:%S"
            ).time()
            new_lunch_break_end = datetime.strptime(
                lunch_break_end_entry.get(), "%H:%M:%S"
            ).time()
            new_end_time = datetime.strptime(end_time_entry.get(), "%H:%M:%S").time()

            start_time = datetime.combine(current_date, new_start_time)
            lunch_break_start = datetime.combine(current_date, new_lunch_break_start)
            lunch_break_end = datetime.combine(current_date, new_lunch_break_end)
            end_time = datetime.combine(current_date, new_end_time)
            settings_window.destroy()
            # 重新初始化时间变量
            last_update_time = datetime.now()  # 重置上次更新时间
        except ValueError:
            tk.messagebox.showerror("错误", "时间格式不正确，请使用HH:MM:SS格式")

    # 应用设置按钮
    apply_button = tk.Button(
        settings_window, text="应用", command=update_times, font=("Arial", 12)
    )
    apply_button.pack(pady=10)


# 创建主窗口
root = tk.Tk()
root.title("下班倒计时") # 窗口标题
root.overrideredirect(True)  # 移除窗口边框和标题栏
root.attributes("-alpha", 0.5)  # 设置窗口透明度（0.0 到 1.0）
root.configure(bg="white")  # 设置窗口背景颜色

# 设置窗口初始位置到屏幕右上角
screen_width = root.winfo_screenwidth() # 获取屏幕宽度
screen_height = root.winfo_screenheight() # 获取屏幕高度
window_width = 300  # 设置窗口宽度
window_height = 100  # 设置窗口高度
root.geometry(f"{window_width}x{window_height}+{screen_width - window_width}+0") # 设置窗口位置和大小

# 禁止调整窗口大小
root.resizable(False, False)

# 创建标签用于显示倒计时
label = tk.Label(root, text="", font=("Arial", 13), bg="white", fg="red")
label.pack(pady=20)

# 创建设置按钮
settings_button = tk.Button(
    root,
    text="设置",
    command=open_settings,
    font=("Arial", 12),
    bg="white",
    fg="blue",
    width=10,
    height=1,
)
settings_button.pack(side=tk.LEFT, padx=5, pady=5)

# 创建关闭按钮
close_button = tk.Button(
    root,
    text="关闭",
    command=close_window,
    font=("Arial", 14),
    bg="white",
    fg="blue",
    width=10,
    height=1,
)
close_button.pack(side=tk.RIGHT, padx=5, pady=5)

# 初始化鼠标拖动变量
x_start, y_start = 0, 0

# 绑定鼠标事件
root.bind("<ButtonPress-1>", start_move)
root.bind("<ButtonRelease-1>", stop_move)
root.bind("<B1-Motion>", do_move)

# 启动倒计时
update_countdown()

# 运行主循环
root.mainloop()
